package vn.edu.ptithcm.pim.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.common.bean.FileUploadBean;
import vn.edu.ptithcm.pim.common.bean.MultiPartFileUploadBean;
import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Company;
import vn.edu.ptithcm.pim.dom.Resource;
import vn.edu.ptithcm.pim.dom.User;
import vn.edu.ptithcm.pim.service.CompanyService;
import vn.edu.ptithcm.pim.service.ResourceService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.DocumentUtil;
import vn.edu.ptithcm.pim.util.FileUtil;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class HandleSlideShowController extends SimpleFormController {
	private UserService userService;
	private ResourceService resourceService;
	private CompanyService companyService;

	Log log = LogFactory.getLog(HandleSlideShowController.class);

	public HandleSlideShowController() {
		super();
		setSessionForm(true);
		setCommandName("slideShowBean");
		setCommandClass(MultiPartFileUploadBean.class);
		setFormView(UrlConstants.HANDLE_SLIDE_SHOW_URL);
		setSuccessView(UrlConstants.HOME_PAGE_URL);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return new MultiPartFileUploadBean();
	}

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		MultiPartFileUploadBean fileUploadBean = (MultiPartFileUploadBean) command;

		String loginName = userService.getCurrentLogin(request);
		User user = userService.findByLoginName(loginName);

		if (user != null) {
			String visa = user.getEmployee().getVisa();

			if (fileUploadBean.getFileUploadBeans() != null) {

				int n = fileUploadBean.getFileUploadBeans().size();

				if (n > 0) {

					for (int i = 0; i < n; ++i) {

						FileUploadBean uploadBean = fileUploadBean
								.getFileUploadBeans().get(i);

						if (uploadBean.getFile() != null
								&& uploadBean.getFile().getSize() > 0) {

							MultipartFile file = uploadBean.getFile();

							String fileName = file.getOriginalFilename();
							String rootPath = request.getSession()
									.getServletContext().getRealPath("");

							String pathToFile = FileUtil.transferTo(file,
									rootPath, Constants.UPLOADED_FILE_FOLDER);
							Date now = new Date();

							String cmd = ParamUtil
									.getString(request, "cmd", "");

							if (cmd.equals("add")) {
								Resource resource = new Resource();
								resource.setTitle(uploadBean.getTitle());
								resource.setAuthor(visa);
								resource.setCreatedAt(now);
								resource.setOrignalName(DocumentUtil
										.getFileName(fileName));
								resource.setPath(pathToFile);

								Company company = (Company) companyService
										.getAll().get(0);
								resource.setSubjectId(company.getCompanyid());
								resource.setSubjectType("SlideShow");
								resource.setType(DocumentUtil
										.getFileExtension(fileName));

								int index = StringUtils
										.indexOf(rootPath, "pim");
								rootPath = rootPath.substring(0, index);

								resource.setSize(FileUtil
										.getSizeInKByte(rootPath + pathToFile));

								resourceService.save(resource);

							} else if (cmd.equals("edit")) {

								Resource resource = resourceService
										.findById(uploadBean.getId());

								resource.setTitle(uploadBean.getTitle());
								resource.setUpdatedBy(visa);
								resource.setLastUpdated(now);
								resource.setOrignalName(DocumentUtil
										.getFileName(fileName));
								resource.setPath(pathToFile);

								Company company = (Company) companyService
										.getAll().get(0);
								resource.setSubjectId(company.getCompanyid());
								resource.setSubjectType("SlideShow");
								resource.setType(DocumentUtil
										.getFileExtension(fileName));

								int index = StringUtils
										.indexOf(rootPath, "pim");
								rootPath = rootPath.substring(0, index);

								resource.setSize(FileUtil
										.getSizeInKByte(rootPath + pathToFile));

								resourceService.saveOrUpdate(resource);
							}
						}
					}
				}
			}
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return showForm(request, response, errors);
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		if (userService.isSignedIn(request)) {
			Map<String, Object> bean = new HashMap<String, Object>();
			String loginName = userService.getCurrentLogin(request);
			User user = userService.findByLoginName(loginName);
			bean.put("user", user);
			bean.put("isSigned", true);
			bean.put("isAdmin", userService.isAdmin(loginName));
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));
			bean.put("visa", user.getEmployee().getVisa());

			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			bean.put(Constants.CMD, cmd);

			String returnToFullPageURL = ParamUtil.getString(request,
					Constants.RETURN_TO_FULL_PAGE_URL, "");

			if (returnToFullPageURL.isEmpty()) {
				returnToFullPageURL = request.getHeader("referer");
			}
			bean.put(Constants.RETURN_TO_FULL_PAGE_URL, returnToFullPageURL);

			List<Resource> slideShowList = resourceService
					.getResourcesForSlideShow(5);
			int slideShowCount = slideShowList.size();

			if (slideShowCount == 0) {
				slideShowCount = 5;
				for (int i = 0; i < slideShowCount; ++i) {
					slideShowList.add(new Resource());
				}
			}

			bean.put("slideShowCount", slideShowCount);
			bean.put("slideShowList", slideShowList);

			request.setAttribute("bean", bean);
		} else {
			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			String redirectLink = UrlConstants.HANDLE_SLIDE_SHOW_URL
					+ UrlConstants.HTM + "?cmd=" + cmd;

			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return super.showForm(request, response, errors);
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ResourceService getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

}
